package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.common.business.utils.WebClientUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.JiKeGongYuanParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 极客公园文章全部导入
 * Created by 黑米 on 2017/3/9.
 */
@Service
public class JiKeGongYuanCrawler extends BaseCrawler {
    Logger logger = LoggerFactory.getLogger(JiKeGongYuanCrawler.class);

    @Autowired
    private JiKeGongYuanParser jiKeGongYuanParser;
    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Override
    protected String url() {
        return CrawlConstant.JIKEGONGYUAN_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.JIKEGONGYUAN_TAG;
    }

    @Override
    protected String avatarSelect() {
        return "a.avatar>img";
    }

    @Override
    protected String channelNameSelect() {
        return "div.title>a";
    }

    /**
     * 频道名称是否同时是作者名称
     *
     * @return 是、否
     */
    @Override
    protected boolean isAuthorName() {
        return true;
    }

    @Override
    protected String listSelect() {
        return "article.article-item";
    }

    @Override
    protected String titleSelect() {
        return "a.article-title";
    }

    @Override
    protected String authorLink() {
        return null;
    }

    @Override
    protected String authorSelect() {
        return "div.title>a";
    }

    /*
     极客早知道
     http://www.geekpark.net/articles_list?page=2&collection=74&category=true
     产品观察
     http://www.geekpark.net/articles_list?page=2&collection=85&category=true
     深度报道
     http://www.geekpark.net/articles_list?page=2&collection=177&category=true
     极客之选
     http://www.geekpark.net/articles_list?page=2&collection=81&category=true
     AR/VR
     http://www.geekpark.net/articles_list?page=2&collection=176&category=true
     挖App
     http://www.geekpark.net/articles_list?page=2&collection=170&category=true
     完全极客养成指南
     http://www.geekpark.net/articles_list?page=2&collection=91&category=true
      */


    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章
        String s = "http://www.geekpark.net/articles_list?page=";
        int totalAll = 0;
        String[] collections = new String[]{"74", "85", "177", "81", "176", "170", "91"};

        try {
            for (String collection : collections) {
                int page = 1;
                WebClientUtil.wc = webClientUtil.initWc(false, false, true);
                int ero = 1;
                while (page <= CrawlConstant.CRAWL_PAGE_TOTAL) {
                    doc = webClientUtil.getDoc(s + page + "&collection=" + collection + "&category=true");
                    //可能是网络延迟问题，有时候文章列表获取失败，其实是好的，所以此处容错五次
                    if (doc == null) {
                        ero++;
                        Thread.sleep(60000);
                        if (ero > 5) {
                            return error("连续五次解析文章失败：" + s + page + "&collection=" + collection + "&category=true");
                        }
                        continue;
                    }
                    ero = 1;
                    JsonResult result = iterate(authorId, doc);
                    if (!result.isSuccess()) {
                        return result;
                    }
                    totalAll += result.getInt();
                    if (!all && result.getInt() < 1) {
                        break;
                    }
                    page++;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult iterate(int authorId, Document doc, String listSelect, String titleSelect) {
        Elements elements = doc.select(listSelect);
        if (elements.size() == 0) {
            return success(0);
        }
        int succ = 0;
        int exist = 0;
        for (Element element : elements) {
            // 获取标题、链接元素
            Element ele = element.select(titleSelect).first();
            if (ele != null) {
                if (element.select("a.article-author").first().text().equals("黑板报值日生")) {
                    continue;
                }
                try {
                    // 校验作者、标题是否已存在
                    Article article = articleCrawlMapper.queryByAuthorTitle(authorId, ele.text().trim());
                    if (article != null) {
                        exist++;
                        if (exist >= 6 && succ == 0) {
                            return success(0);
                        }
                        continue;
                    }
                    String href = ele.attr("href");
                    if (StringUtils.isBlank(href)) {
                        return error("文章链接解析失败");
                    }
                    href = "http://www.geekpark.net" + href;
                    JsonResult result = parse(authorId, href);
                    succ += result.isSuccess() ? 1 : 0;
                } catch (Exception e) {
                    logger.error("Parser.parse error,{}", ele, e);
                    return error(CommonConstant.ABNORMAL_MSG);
                }
            }
        }
        return success(succ);
    }


    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return jiKeGongYuanParser.parse(authorId, link);
    }

    @Override
    protected String getBody(Document doc) {
        return jiKeGongYuanParser.getBody(doc);
    }
}
